from rest_framework.generics import CreateAPIView, GenericAPIView, RetrieveUpdateAPIView, RetrieveAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from django.db.models import Q
from apps.user.utils import CalendarUtils
from utils.message import Message
from . import models as user_model
from . import serializers as user_serializer
from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, ListModelMixin
import datetime


class CreateUserView(CreateAPIView):
    """用户注册"""
    serializer_class = user_serializer.CreateUserSerializer


class UserView(RetrieveUpdateAPIView):
    """用户修改、查看"""
    queryset = user_model.User.objects.all()
    serializer_class = user_serializer.UserDetailSerializer


class UserListView(GenericViewSet, ListModelMixin):
    queryset = user_serializer.User.objects.all()
    serializer_class = user_serializer.UserDetailSerializer


class UserStatisticsView(APIView):
    """统计注册用户: 本月、 日"""
    calendar = CalendarUtils()
    message = Message()

    def get(self, request):
        """
        query_params day or week or None当天, 本周
        :param request:
        :return:
        """
        condition = self.get_condition(request.query_params)  # 获取查询对象
        num = user_model.User.objects.filter(condition).count()  # 获取数量
        result = self.message.success
        result.update({'count': num})
        return Response(result)

    @staticmethod
    def get_condition(param):
        today = datetime.date.today()
        year = today.year
        month = today.month
        day = today.day
        query = Q()
        query.connector = 'AND'
        query.children.append(('create_time__year', year))
        if param.get('month', None) is not None:
            query.children.append(('create_time__month', month))
        else:
            query.children.append(('create_time__month', month))
            query.children.append(('create_time__day', day))
        return query
